package com.nopay.dxdwphone.ui.ativity;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.dxdwphone.base.BaseActivity;
import com.nopay.dxdwphone.bean.CommonResponse;
import com.nopay.dxdwphone.bean.response.GetCallTaskGroupResponse;
import com.nopay.dxdwphone.dialog.DialogDownload;
import com.nopay.dxdwphone.dialog.DialogHasNewVersion;
import com.nopay.dxdwphone.ui.fragment.CallLogFragment;
import com.nopay.dxdwphone.ui.fragment.OutboundFragment;
import com.nopay.dxdwphone.ui.fragment.PersonFragment;
import com.nopay.dxdwphone.ui.fragment.StatisticsFragment;
import com.nopay.dxdwphone.utils.UpdateUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.nopay.dxdwphone.Constants;
import com.nopay.dxdwphone.R;

import com.nopay.dxdwphone.ui.adapter.MyFragmentAdapter;

import com.nopay.dxdwphone.databinding.ActivityMainBinding;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends BaseActivity<ActivityMainBinding> {

    private List<Fragment> mFragmentList = new ArrayList<>();
    private List<String> mTitleList = new ArrayList<>();
    private MyFragmentAdapter myFragmentAdapter;
    private StatisticsFragment statisticsFragment;
    private OutboundFragment outboundFragment;
    private PersonFragment personFragment;
    private CallLogFragment callLogFragment;

    private String versionName= "";

    @Override
    protected void init(Bundle savedInstanceState, Object... preData) {
        statisticsFragment = new StatisticsFragment();
        outboundFragment = new OutboundFragment();
        personFragment = new PersonFragment();
        callLogFragment = new CallLogFragment();
        mFragmentList.add(statisticsFragment);
        mFragmentList.add(callLogFragment);
        mFragmentList.add(outboundFragment);
        mFragmentList.add(personFragment);
        mTitleList.add("统计");
        mTitleList.add("通话记录");
        mTitleList.add("拨号");
        mTitleList.add("设置");
        binding.orderTab.setupWithViewPager(binding.orderViewPager);
        binding.orderViewPager.setOffscreenPageLimit(3);
        myFragmentAdapter = new MyFragmentAdapter(mFragmentList, mTitleList, getSupportFragmentManager());
        binding.orderViewPager.setAdapter(myFragmentAdapter);
        binding.orderViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if(position == 0) {
                    statisticsFragment.refreshData();
                }

                if(position == 1) {
                    callLogFragment.refreshData();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        binding.orderTab.getTabAt(0).setIcon(R.drawable.selector_tab_icon__statistics).select();
        binding.orderTab.getTabAt(1).setIcon(R.drawable.selector_tab_icon_call_log);
        binding.orderTab.getTabAt(2).setIcon(R.drawable.selector_tab_icon_dial);
        binding.orderTab.getTabAt(3).setIcon(R.drawable.selector_tab_icon_setting);

        try {
            versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        checkVersion(false);
    }

    @Override
    protected boolean setCanTwoBackCloseApp() {
        return true;
    }

    public void gotoAcountInfo(){
        mSwipeBackHelper.forward(AcountInfoActivity.class);
    }

    public void gotoFileImport(){
        mSwipeBackHelper.forward(FileImportActivity.class, Constants.REQ_OPEN_FILE);
    }

    public void gotoTel(){
        mSwipeBackHelper.forward(ManualDialingActivity.class);
    }

    public void gotoCallTask(GetCallTaskGroupResponse.Data group){
        Intent intent = new Intent(MainActivity.this, CallTaskDetailActivity.class);
        intent.putExtra(Constants._CALL_TASK_GROUP, group);
        mSwipeBackHelper.forward(intent, Constants.REQ_CALL_TASK_DELETE);
    }

    public void gotoFeedBack(){
        mSwipeBackHelper.forward(FeedBackActivity.class);
    }

    public void gotoHelp(){
        mSwipeBackHelper.forward(HelpActivity.class);
    }

    public void gotoInvist(){
//        mSwipeBackHelper.forward(InvistActivity.class);
        mSwipeBackHelper.forward(InviteFriendsActivity.class);
    }

    public void gotoTextCourse(){
        mSwipeBackHelper.forward(TextCourseActivity.class);
    }

    public void gotoVideoCourse(){
        mSwipeBackHelper.forward(VideoCourseActivity.class);
    }

    public void gotoProblemAnswer(){
        mSwipeBackHelper.forward(ProblemAnswerActivity.class);
    }

    public void gotoCallSetting(){
//        if(!MemberManager.hasMemberPermission()) {
//            // TODO 提示开通会员才能使用
//            new DialogPleaseOpenMember(MainActivity.this).setOnOpenMemberConfirmListener(() -> {
//                // TODO 确认开通会员
//                gotoRecharge();
//            }).show();
//            return;
//        }

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 120);
            return;
        }

//        int simStatus = CallTransferUtil.getSIMStatus(MainActivity.this);
//        if(simStatus == -1) {
//            ToastUtils.showShort("请插入SIM卡");
//            return;
//        }
//        mSwipeBackHelper.forward(simStatus  == 2 ? CallSettingForDoubleSIMActivity.class : CallSettingForSingleSIMActivity.class);

//        mSwipeBackHelper.forward(CallSettingForSingleSIMActivity.class);

        mSwipeBackHelper.forward(CallSettingActivity.class);
    }

//    public void gotoRecharge(){
//        mSwipeBackHelper.forward(RechargeActivity.class);
//    }

    public void gotoCallLogExport(){
        mSwipeBackHelper.forward(CallLogExportActivity.class);
    }

    public void gotoAuth(){
        mSwipeBackHelper.forward(AuthorityActivity.class);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK) {
            if (requestCode == Constants.REQ_OPEN_FILE) {
                String taskName = data.getStringExtra(Constants.FILE_IMPORT_TASK_NAME);
//                outboundFragment.addImportTask(taskName);
            }

            if (requestCode == Constants.REQ_CALL_TASK_DELETE) {
                boolean isDelete = data.getBooleanExtra("IS_DELETE", false);
                if(isDelete) outboundFragment.hasTaskClear();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {//选择了“始终允许”
                    ToastUtils.showShort("" + "权限" + permissions[i] + "申请成功");
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "10086"));
                    startActivity(intent);
                }else{
                    ToastUtils.showShort("请给用户授权");
                }
            }
        }
        if (requestCode == 2) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {//选择了“始终允许”
                    ToastUtils.showShort("" + "权限" + permissions[i] + "申请成功");
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "10010"));
                    startActivity(intent);
                }else{
                    ToastUtils.showShort("请给用户授权");
                }
            }
        }

        if (requestCode == 100) {
            gotoTel();
        }

        if (requestCode == 101) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    gotoFileImport();
                }else{
                    ToastUtils.showShort("请给用户授权");
                }
            }
        }
    }

    public String getVersionName() {
        return versionName;
    }

    public void checkVersion() {
        checkVersion(true);
    }

    public void checkVersion(boolean showToast) {
        api.doGetVersion().enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        String newestVersion = response.body().getMsg();
                        if(versionName.equals(newestVersion)) {
                            if(showToast) ToastUtils.showShort("已是最新版本");
                        } else {
                            // TODO 提示版本更新
                            new DialogHasNewVersion(MainActivity.this).setOnUpdateConfirmListener(() -> {
                                // TODO 确认更新
                                downloadApk();
                            }).show();
                        }
                    } else {
                        if(showToast) ToastUtils.showShort("已是最新版本");
                    }
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                if(showToast) ToastUtils.showShort(getResources().getString(R.string.call_api_error));
            }
        });
    }

    private void downloadApk() {
        DialogDownload dialogDownload = new DialogDownload(MainActivity.this);
        dialogDownload.show();
        UpdateUtil.downloadApk(new UpdateUtil.OnDownloadApkListener() {
            @Override
            public void inProgress(int progress) {
                runOnUiThread(() -> dialogDownload.setProgress(progress));
            }

            @Override
            public void onSuccess(File apkFile) {
                runOnUiThread(() -> {
                    dialogDownload.dismiss();
                    UpdateUtil.install(MainActivity.this);
                });
            }

            @Override
            public void onError(Throwable e) {
                dialogDownload.dismiss();
                ToastUtils.showShort("下载失败");
            }
        });
    }

}